package cn.dhnep.demo.controller;

import cn.dhnep.demo.pojo.vo.RespBean;
import cn.dhnep.demo.pojo.vo.Results;
import cn.dhnep.demo.util.HttpClientUtil;
import cn.dhnep.demo.util.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取传感器信息
 */
@RestController
@RequestMapping("/wxshop/recycle")
public class QueryRecycleController {

    @Resource
    private RedisUtil redisUtil;

    @ApiOperation("授权获取用户token")
    @GetMapping("/getToken")
    public RespBean getToken(){
        String url = "https://rest.hive-intel.com/web/auth/token";
        Map<String, String> body = new HashMap<>();
        body.put("passport","dhnjyf1");
        body.put("password","123123");

        String res = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(body));
        RespBean bean = JSONObject.parseObject(res, RespBean.class);
        Map<String,Object> resMap = ((Map<String,Object>) bean.getContent());
        Object o = ((List<?>) resMap.get("results")).get(0);
        Results results = JSONObject.parseObject(o.toString(), Results.class);
        return RespBean.success(null,results.getAccessToken());
    }

    @ApiOperation("获取所有传感器信息")
    @GetMapping("/getSensor")
    public RespBean getAllSensor(){
        if (redisUtil.hasKey("sensors")) {
            return RespBean.success(null,redisUtil.get("sensors"));
        }
        String token = "6114de1fe25583000137d3dc";
        String url = "https://rest.hive-intel.com/web/sensors?token=" + token;
        String res = HttpClientUtil.doGet(url);

        RespBean bean = JSONObject.parseObject(res, RespBean.class);
        //存入redis中，设置过期时间三分钟
        if(bean.getCode() == 0 && redisUtil.set("sensors",bean.getContent(),180)){
            //TODO 回收柜已满通知骑手
            return RespBean.success(null,bean.getContent());
        }
        return RespBean.error("获取传感器信息失败！");

    }
}
